# -*- coding: utf-8 -*-
import json
import time

import websocket
import requests
try:
    import thread
except ImportError:
    import _thread as thread


class WsClient:
    acc_ws_url = "ws://127.0.0.1:8891/acc?token="

    @staticmethod
    def on_message(wsApp, message):
        print("收到：" + message)

    @staticmethod
    def on_error(wsApp, error):
        print("发生异常：" + error)

    @staticmethod
    def on_close(wsApp):
        print("### closed ###")

    @staticmethod
    def on_open(wsApp):
        def hb_run(*args):
            while True:
                time.sleep(5)
                wsApp.send(json.dumps(
                    {"ModuleID": "861", "ModuleStatus": 1, "MsgID": "HBReq", "MsgTime": "2020-06-04 09:17:11.150"}))

        def call_run(*args):
            while True:
                time.sleep(20)
                print("发送呼叫请求")
                wsApp.send(json.dumps(
                    {"MsgID": "IMLoginReq", "ModuleID": "999", "MsgTime": "2020-06-02 21:55:56.311", "TokenID": 10000,
                     "UserID": 409, "Caller": "13800138000", "CompanyId": "360000000000000000", "ProductId": "",
                     "Called": "680680",
                     "LoginType": "1", "WeChatID": "", "WXAppId": "wx9c72795e3b1d48cf", "ActivityName": "演示活动",
                     "ProductBrand": "咪码科技", "ProductTitle": "演示测试", "ProductCode": "8888", "Reserved": ""}))

        thread.start_new_thread(hb_run, ())
        thread.start_new_thread(call_run, ())

    def run(self, token_value):
        websocket.enableTrace(True)
        ws = websocket.WebSocketApp(self.acc_ws_url + token_value,
                                    on_message=self.on_message,
                                    on_error=self.on_error,
                                    on_close=self.on_close)
        ws.on_open = self.on_open
        # ws.run_forever(ping_interval=10, ping_timeout=5)
        ws.run_forever()


class HttpClient:
    http_url = "http://127.0.0.1:8801/app-wechat/loginApi/loginForTest"
    params = {"key": 409}

    def run(self):
        session = requests.Session()
        response = session.post(url=self.http_url,
                                data=json.dumps(self.params))
        result = response.json()
        return result["data"]["data"]["token"]


if __name__ == "__main__":
    print('*' * 50)
    print('深圳市咪码科技有限公司')
    print('WebSocket Client v1.0')
    print('2020年6月4日')
    print('*' * 50)
    token = HttpClient().run()
    WsClient().run(token)
